#pragma once

#include <iostream>
#include <string>
#include "mutex.hpp"
#include <memory>
#include <time.h>
#include <filesystem>
#include <fstream>
#include <sys/types.h>
#include <unistd.h>
#include <sstream>


namespace LogModule
{
    // 策略模式
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void Synclog(const std::string &message) = 0;
    };
    // 控制台策略
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ConsoleLogStrategy() {}
        ~ConsoleLogStrategy() {}

        virtual void Synclog(const std::string &message)
        {
            LockModule::LockGuard lg(_mutex);
            std::cout << message << std::endl;
        }

    private:
        LockModule::Mutex _mutex;
    };

    const std::string default_logpath = "./log/";
    const std::string default_logname = "log.txt";
    // 文件策略
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &logpath = default_logpath, const std::string &logname = default_logname)
            : _logpath(logpath), _logname(logname)
        {
            // 检查_logpath是否存在
            if (std::filesystem::exists(_logpath))
            {
                // 存在
                return;
            }
            // 不存在
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << "\n";
            }
        };
        ~FileLogStrategy() {};
        virtual void Synclog(const std::string &message)
        {
            LockModule::LockGuard lg(_mutex);
            // 文件名即路径
            std::string log = _logpath + _logname;
            std::ofstream fout(log, std::ios::app);
            if (!fout.is_open())
            {
                return;
            }
            fout << message << "\n";
            fout.close();
        };

    private:
        std::string _logpath;
        std::string _logname;
        LockModule::Mutex _mutex;
    };

    enum LogLevel
    {
        DEBUG = 1,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    // 日志类
    class logger
    {
    public:
        logger()
        {
            // 默认采用控制台策略
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableConsoleLog()
        {
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableFileLog()
        {
            _strategy = std::make_shared<FileLogStrategy>();
        }

        // 日志等级转字符串
        std::string LogLevel2String(LogLevel level)
        {
            switch (level)
            {
            case DEBUG:
                return "DEBUG";
                break;
            case INFO:
                return "INFO";
                break;
            case WARNING:
                return "WARNING";
                break;
            case ERROR:
                return "ERROR";
                break;
            case FATAL:
                return "FATAL";
                break;
            default:
                return "None";
            }
        }

        std::string CurrentTime()
        {
            time_t time_stamp = ::time(nullptr);
            struct tm cur;
            localtime_r(&time_stamp, &cur);

            char buffer[1024];
            snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d",
                     cur.tm_year + 1900,
                     cur.tm_mon + 1,
                     cur.tm_mday,
                     cur.tm_hour,
                     cur.tm_min,
                     cur.tm_sec);
            return buffer;
        }

        // 日志信息格式
        class logmessage
        {
        public:
            logmessage(LogLevel level, const std::string &filename, int line, logger &logger)
                : _curtime(logger.CurrentTime()), _level(level), _pid(::getpid()), _filename(filename), _line(line), _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _curtime << "]"
                         << "[" << logger.LogLevel2String(_level) << "]"
                         << "[" << _pid << "]"
                         << "[" << _filename << "]"
                         << "[" << _line << "] - ";
                _loginfo = ssbuffer.str();
            }
            // 利用生命周期调用策略
            ~logmessage()
            {
                if (_logger._strategy)
                    _logger._strategy->Synclog(_loginfo);
            }

            template<class T>
            logmessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

        private:
            std::string _curtime;  // 日志当前时间
            LogLevel _level;       // 日志等级
            pid_t _pid;            // 进程pid
            std::string _filename; // 源文件名
            int _line;             // 日志所在行号
            logger &_logger;       // 用于获取策略
            std::string _loginfo;  // 完整的一条日志信息
        };
        // 用logger拷贝构造 返回临时logmessage对象
        logmessage operator()(LogLevel level, std::string filename, int line)
        {
            return logmessage(level, filename, line, *this);
        }

    private:
        std::shared_ptr<LogStrategy> _strategy;
    };
    //定义一个全局日志类
    logger log;

//注意末尾不要加 ';'
#define LOG(level) log(level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG() log.EnableConsoleLog()
#define ENABLE_FILE_LOG() log.EnableFileLog()
}